package org.springblade.modules.icivil.task;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.common.cache.StressCache;
import org.springblade.common.constant.StressConstant;
import org.springblade.core.http.HttpRequest;
import org.springblade.core.http.ResponseSpec;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.utils.DateTimeUtil;
import org.springblade.modules.icivil.entity.*;
import org.springblade.modules.stress.entity.*;
import org.springblade.modules.stress.service.*;
import org.springblade.modules.stress.vo.ChannelVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.net.URI;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *更新数据值的处理方式是：两个不同的定时器任务，一个插入数据到缓存并存储到数据库，同时判断是否预警，一个读取缓存数据发送到前段
 *
 *
 *
 *
 *
 */

@Component
public class DataTask {
	@Autowired
	private BladeRedis bladeRedis;
	@Autowired
	private SimpMessagingTemplate messagingTemplate;
	@Autowired
	private IDeviceService deviceService;
	@Autowired
	private IChannelService channelService;
	@Autowired
	private ISensorService sensorService;
	@Autowired
	private IHistoryService historyService;
	@Autowired
	private IWarningService warningService;

	/*********************************实时更新数据*****************************************************************/
	//@Scheduled(cron = "0 15 10 ? * MON-FRI")//周一至周五的上午10:15触发
	//@Scheduled(cron = "30 * * * * ?")//每半分钟触发
	@Scheduled(cron = "*/5 * * * * ?")//每60秒触发
	@Async
	public void taskRunSendToWebsocket() throws Exception {
		sendTowerCraneData();
		sendTrotalCraneData();
		sendParachuteData();
	}

	//推送数据websokect:塔式起重机
	public void sendTowerCraneData(){
		//List<CraneData> list = getResDataFromRedis(StressConstant.STRESS_DEVICE_TYPE_TOWER_CRANE);
		List<CraneData> list = getUpdateDataFromRedis(StressConstant.STRESS_DEVICE_TYPE_TOWER_CRANE);
		TowerDataVo craneDataVo = new TowerDataVo();
		craneDataVo.setTowerType(StressConstant.STRESS_DEVICE_TYPE_TOWER_CRANE);
		craneDataVo.setTowerList(list);
		messagingTemplate.convertAndSendToUser("000000","/queue/getResponse",craneDataVo);
	}

	//推送数据websokect:门座式起重机
	public void sendTrotalCraneData(){
		//List<CraneData> list = getResDataFromRedis(StressConstant.STRESS_DEVICE_TYPE_TROTAL_CRANE);
		List<CraneData> list = getUpdateDataFromRedis(StressConstant.STRESS_DEVICE_TYPE_TROTAL_CRANE);
		TrotalDataVo craneDataVo = new TrotalDataVo();
		craneDataVo.setTrotalType(StressConstant.STRESS_DEVICE_TYPE_TROTAL_CRANE);
		craneDataVo.setTrotalList(list);
		messagingTemplate.convertAndSendToUser("000000","/queue/getResponse",craneDataVo);
	}

	//推送数据websokect:防坠器起重机
	public void sendParachuteData(){
		//List<CraneData> list = getResDataFromRedis(StressConstant.STRESS_DEVICE_TYPE_PARACHUTE);
		List<CraneData> list = getUpdateDataFromRedis(StressConstant.STRESS_DEVICE_TYPE_PARACHUTE);
		ParachuteDataVo craneDataVo = new ParachuteDataVo();
		craneDataVo.setParachuteType(StressConstant.STRESS_DEVICE_TYPE_PARACHUTE);
		craneDataVo.setParachuteList(list);
		messagingTemplate.convertAndSendToUser("000000","/queue/getResponse",craneDataVo);
	}

	//从Redis获取起重机实时数据
	public List<CraneData> getUpdateDataFromRedis(Integer type){
		List<CraneData> list = new ArrayList<>();
		List<PositionData> pdList = getPositionIndexFromRedis(type);
		for (PositionData pd: pdList) {
			CraneData cd = new CraneData();
			cd.setChannelId(pd.getPositionId());
			cd.setName(pd.getName());

			String positionKey = "online:" + pd.getPositionId() ;
			Boolean isExists = bladeRedis.exists(positionKey);
			if (isExists){
				PositionOnlineData pod = bladeRedis.get(positionKey);
				cd.setSampleValue(pod.getStressValue());
				cd.setStatusTypeName(pod.getOnlineStatus());
			}else {
				cd.setSampleValue("0.00");
				cd.setStatusTypeName("正常");
			}
			list.add(cd);
		}

		return list;
	}

	/*********************************获取测点索引数据*****************************************************************/
	//从Redis获取起重机测点索引
	public List<PositionData> getPositionIndexFromRedis(Integer type){
		List<Device> deviceList = deviceService.list(Wrappers.<Device>query().lambda().eq(Device::getDeviceType, type));
		if (deviceList.size() > 0){
			Device device = deviceList.get(0);
			String deviceId = device.getId().toString();
			//获取设备的测点索引列表
			List<PositionData> pdList = bladeRedis.get("position:" + deviceId);
			return pdList;
		}
		return null;
	}



	/*********************************插入数据*****************************************************************/
//	@Scheduled(cron = "*/30 * * * * ?")//每30秒触发
	@Scheduled(cron = "0 */10 * * * ?")
    @Async
	public void handleAllDataFromHttp(){

		//塔机数据
		getCraneDataFromHttp(StressConstant.STRESS_DEVICE_TYPE_TOWER_CRANE);

		//门机数据
		getCraneDataFromHttp(StressConstant.STRESS_DEVICE_TYPE_TROTAL_CRANE);

		//防坠器
		getCraneDataFromHttp(StressConstant.STRESS_DEVICE_TYPE_PARACHUTE);

	}

	public void getCraneDataFromHttp(Integer type){
		List<PositionData> pdList = getPositionIndexFromRedis(type);
		for (PositionData index: pdList) {
			//解析时间
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			long currentTime = System.currentTimeMillis();
			long startTime = currentTime - 30 * 60 * 1000;

			handleCraneDataFromHttp(index,startTime,currentTime);
		}
	}

	@Transactional
	public void handleCraneDataFromHttp(PositionData index,long startTime,long currentTime){
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//确定时间范围
		String end = df.format(new Date(currentTime));
		String start = df.format(new Date(startTime));
		//振弦数据
		String vgKey = "sensor:" + index.getPositionId() + ":" + StressConstant.STRESS_SENSOR_TYPE_VIBRATING;
		FirstData fdVg = bladeRedis.get(vgKey);
		PageResData prdVg = getDataFromHttpRequest(fdVg.getSensorCode(),fdVg.getChannelCode(),start,end);

		//温度数据
		String tmKey = "sensor:" + index.getPositionId() + ":" + StressConstant.STRESS_SENSOR_TYPE_TEMPERATURE;
		FirstData fdTe = bladeRedis.get(tmKey);
		PageResData prdTe = getDataFromHttpRequest(fdTe.getSensorCode(),fdTe.getChannelCode(),start,end);
		//时间推前半小时
		if (prdTe.getTotalCount() == 0 && prdVg.getTotalCount() == 0){
			long sTime = currentTime - 60 * 60 * 1000;
			Date sDate = new Date(sTime);
			String startStr= df.format(sDate);
			//振弦数据
			prdVg = getDataFromHttpRequest(fdVg.getSensorCode(),fdVg.getChannelCode(),startStr,start);

			//温度数据
			prdTe = getDataFromHttpRequest(fdTe.getSensorCode(),fdTe.getChannelCode(),startStr,start);
		}

//		System.out.println(prdVg.getTotalCount());
//		System.out.println(prdTe.getTotalCount());

		//初始值
		String fVg = fdVg.getFirstValue();//振弦频率初始值
		String fTe = fdTe.getFirstValue();//温度初始值

		//实时值
		String vVg = prdVg.getList().get(0).getPntValue();//振弦频率
		String vTe = prdTe.getList().get(0).getPntValue();//温度

		//公式计算
		Double onlineValue = handleStreeValue(fVg,fTe,vVg,vTe);
//		System.out.println("振弦频率: "+vVg);
//		System.out.println("振弦频率初始值: "+fVg);
//		System.out.println("温度: "+vTe);
//		System.out.println("温度初始值: "+fTe);;
//		System.out.println("应力值: " + onlineValue);

		PositionOnlineData pod = new PositionOnlineData();
		pod.setPositionId(index.getPositionId());
		pod.setCreated(prdVg.getList().get(0).getCreated());
		pod.setSensorCode(fdVg.getSensorCode());
		pod.setVgChannelCode(fdVg.getChannelCode());
		pod.setTeChannelCode(fdTe.getChannelCode());
		pod.setVgFirst(fVg);
		pod.setTeFirst(fTe);
		pod.setVgValue(vVg);
		pod.setTeValue(vTe);
		pod.setStressValue(onlineValue.toString());

		//插入预警缓存数据
		String status = handlePositionValueInsertWarning(index.getPositionId(),prdVg.getList().get(0).getCreated(),onlineValue.toString());
		//插入状态
		pod.setOnlineStatus(status);

		//处理最新数据,插入缓存
		handlePositionValueOnlineData(index.getPositionId(),pod);

		//插入时间缓存数据
		//handlePositionValueInsertMysql(index.getPositionId(),prdVg.getList().get(0).getCreated(),onlineValue.toString());

		String value = onlineValue.toString();
		String created = prdVg.getList().get(0).getCreated();
		String positionId = index.getPositionId();
		String key = "mysql:" + index.getPositionId() + ":" + created;
		Boolean keyExsited= bladeRedis.exists(key);

		if (!keyExsited){
			bladeRedis.set(key,value);

			List<History> historyList = historyService.list(Wrappers.<History>query().lambda().eq(History::getPositionId, positionId)
				.eq(History::getStartTime,DateTimeUtil.parseDateTime(created)));
			List<History> addHis = new ArrayList<>();
			if (historyList.size() == 0 && historyList != null){
				//插入应力值
				History history = new History();
				history.setPositionId(Long.parseLong(positionId));
				history.setSampleValue(value);
				history.setSampleUnit("με");
				history.setSampleType(StressConstant.STRESS_SENSOR_TYPE_POSITION);
				history.setStartTime(DateTimeUtil.parseDateTime(created));
				history.setStatus(1);
				addHis.add(history);
				//插入振弦值
				History vgHistory = new History();
				vgHistory.setPositionId(Long.parseLong(positionId));
				vgHistory.setSensorCode(fdVg.getSensorCode());
				vgHistory.setSensorChannel(fdVg.getChannelCode());
				vgHistory.setSampleValue(vVg);
				vgHistory.setSampleUnit("Hz");
				vgHistory.setSensorId(Long.parseLong(fdVg.getSensorId()));
				vgHistory.setSampleType(StressConstant.STRESS_SENSOR_TYPE_VIBRATING);
				vgHistory.setStartTime(DateTimeUtil.parseDateTime(created));
				vgHistory.setStatus(1);
				addHis.add(vgHistory);
				//插入温度值
				History teHistory = new History();
				teHistory.setPositionId(Long.parseLong(positionId));
				teHistory.setSensorCode(fdTe.getSensorCode());
				teHistory.setSensorChannel(fdTe.getChannelCode());
				teHistory.setSampleValue(vTe);
				teHistory.setSampleUnit("℃");
				teHistory.setSensorId(Long.parseLong(fdTe.getSensorId()));
				teHistory.setSampleType(StressConstant.STRESS_SENSOR_TYPE_TEMPERATURE);
				teHistory.setStartTime(DateTimeUtil.parseDateTime(created));
				teHistory.setStatus(1);
				addHis.add(teHistory);

				//批量插入
				historyService.saveBatch(addHis);
			}
		}
	}



	//处理最新数据，保证数据是最新，目的是推送到前段
	public void handlePositionValueOnlineData(String positionId,PositionOnlineData newData){
		String positionKey = "online:" + positionId ;
		Boolean keyExsited= bladeRedis.exists(positionKey);

		if(keyExsited){//有数据
			System.out.println("--------------------存在");
			//获取值 反序列化
			PositionOnlineData oldData = bladeRedis.get(positionKey);
			LocalDateTime oldTime = DateTimeUtil.parseDateTime(oldData.getCreated());
			LocalDateTime newTime = DateTimeUtil.parseDateTime(newData.getCreated());
			if (newTime.isAfter(oldTime)){
				bladeRedis.set(positionKey,newData);
			}
		}else {//没有该数据，插入
			System.out.println("---------------------不存在");
			bladeRedis.set(positionKey,newData);
		}
	}

	//插入实时数据
	public void handlePositionValueInsertMysql(String positionId,String created,String value){
		String key = "mysql:" + positionId + ":" + created;
		Boolean keyExsited= bladeRedis.exists(key);
		if (keyExsited){

		}else {
			bladeRedis.set(key,value);
			List<History> historyList = historyService.list(Wrappers.<History>query().lambda().eq(History::getPositionId, positionId)
				.eq(History::getStartTime,DateTimeUtil.parseDateTime(created)));

			if (historyList.size() == 0 && historyList != null){
				History history = new History();
				history.setPositionId(Long.parseLong(positionId));
				history.setSampleValue(value);
				history.setStartTime(DateTimeUtil.parseDateTime(created));
				history.setStatus(1);
				historyService.save(history);
			}
		}
	}

	public void handlePositionValueInsertMysql(String positionId,FirstData fdVg,FirstData fdTe,String created,String value){
		String key = "mysql:" + positionId + ":" + created;
		Boolean keyExsited= bladeRedis.exists(key);
		if (keyExsited){

		}else {
			bladeRedis.set(key,value);
			List<History> historyList = historyService.list(Wrappers.<History>query().lambda().eq(History::getPositionId, positionId)
				.eq(History::getStartTime,DateTimeUtil.parseDateTime(created)));

			if (historyList.size() == 0 && historyList != null){
				History history = new History();
				history.setPositionId(Long.parseLong(positionId));
				history.setSampleValue(value);
				history.setStartTime(DateTimeUtil.parseDateTime(created));
				history.setStatus(1);
				historyService.save(history);
			}
		}
	}

	//插入预警数据
	public String handlePositionValueInsertWarning(String positionId,String created,String value){
		String key = "alarm:" + positionId +":" +  created;

		Warning warning = new Warning();
		warning.setPositionId(Long.parseLong(positionId));
		warning.setSampleValue(value);
		warning.setStartTime(DateTimeUtil.parseDateTime(created));



		Position position = StressCache.getPosition(Long.parseLong(positionId));
		Alarm high = StressCache.getAlarm(position.getAlarmHighId());
		Alarm low = StressCache.getAlarm(position.getAlarmLowId());
		Double highAlarm = high.getAlarmValue();
		Double lowAlarm = low.getAlarmValue();
		AlarmData alarm = new AlarmData();

		String st = "正常";
		Boolean keyExsited= bladeRedis.exists(key);
		if (keyExsited){

		}else {
			//超上限预警
			if (Double.parseDouble(value) > highAlarm) {
				alarm.setAlarmId(position.getAlarmHighId().toString());
				alarm.setAlarmType(high.getAlarmType().toString());
				alarm.setAlarmValue(highAlarm.toString());
				alarm.setSampleValue(value);
				bladeRedis.set(key, alarm);
				st = "超上限预警";
				warning.setAlarmId(position.getAlarmHighId());

				List<Warning> warningList = warningService.list(Wrappers.<Warning>query().lambda().eq(Warning::getPositionId, positionId)
					.eq(Warning::getStartTime,DateTimeUtil.parseDateTime(created)));

				if (warningList.size() == 0 && warningList != null){
					warningService.save(warning);
				}
			}

			//超下限预警
			if (Double.parseDouble(value) < lowAlarm) {
				alarm.setAlarmId(position.getAlarmLowId().toString());
				alarm.setAlarmType(low.getAlarmType().toString());
				alarm.setAlarmValue(lowAlarm.toString());
				alarm.setSampleValue(value);
				bladeRedis.set(key, alarm);
				st = "超下限预警";
				warning.setAlarmId(position.getAlarmLowId());
				List<Warning> warningList = warningService.list(Wrappers.<Warning>query().lambda().eq(Warning::getPositionId, positionId)
					.eq(Warning::getStartTime,DateTimeUtil.parseDateTime(created)));

				if (warningList.size() == 0 && warningList != null){
					warningService.save(warning);
				}
			}


		}



		return st;
	}

	/**
	 *
	 * @param fVg 频率初始值
	 * @param fTe 温度初始值
	 * @param vVg 频率实时值
	 * @param vTe 温度实时值
	 * @return
	 */
	public Double handleStreeValue(String fVg,String fTe,String vVg,String vTe){
		Double ftFVg = Double.parseDouble(fVg);
		Double ftFTe = Double.parseDouble(fTe);
		Double ftVVg = Double.parseDouble(vVg);
		Double ftVTe = Double.parseDouble(vTe);
		Double value = 0.00136*(ftVVg*ftVVg - ftFVg*ftFVg) + 0.2 * (ftVTe - ftFTe);
		return  Double.valueOf(String.format("%.3f", value));
	}

	//http拉取数据
	public PageResData getDataFromHttpRequest(String sensorCode,String channelCode,String start,String end){
		HttpQueryData query = new HttpQueryData();
		query.setChannel(channelCode);
		query.setNode(sensorCode);
		query.setStart(start);
		query.setEnd(end);
		query.setPage(1);
		String opt1 =HttpRequest.post(URI.create("http://182.92.232.25:6830/partner/channel"))
			.bodyJson(query).execute().onSuccessful(ResponseSpec::asString);
		System.out.println(opt1);
		QueryResult qr = JsonUtil.parse(opt1,QueryResult.class);
		PageResData pgd = qr.getData();

		return pgd;
	}
	/******************************************************************************************************************/

	public PageResData getDataFromHttpRequestByPage(String sensorCode,String channelCode,String start,String end,int page){
		System.out.println(sensorCode);
		System.out.println(channelCode);
		System.out.println(start);
		System.out.println(end);
		HttpQueryData query = new HttpQueryData();
		query.setChannel(channelCode);
		query.setNode(sensorCode);
		query.setStart(start);
		query.setEnd(end);
		query.setPage(page);
		String opt1 =HttpRequest.post(URI.create("http://182.92.232.25:6830/partner/channel"))
			.bodyJson(query).execute().onSuccessful(ResponseSpec::asString);
		System.out.println(opt1);
		QueryResult qr = JsonUtil.parse(opt1,QueryResult.class);
		PageResData pgd = qr.getData();

		return pgd;
	}


	//获取所有数据
	public void getCraneDataAllFromHttp(Integer type){
		List<PositionData> pdList = getPositionIndexFromRedis(type);
		for (PositionData index: pdList) {
			long currentTime = System.currentTimeMillis();
			long time = 1616862500000L;
			long startTime  = 0L;
			long updateTime = 0L;
			long inval = 1000 * 60 * 30;
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for (int i = 0; i < 765; i++) {
				startTime =  time + inval * i;
				updateTime =  time + inval * (i+1);

				System.out.println(df.format(new Date(startTime)));
				System.out.println(df.format(new Date(updateTime)));
				System.out.println("------------------------------");

				if (startTime > currentTime) break;

				handleCraneDataFromHttp(index,startTime,updateTime);
			}
		}
	}

	public void getCraneDataBatchFromHttp(Integer type){
		List<PositionData> pdList = getPositionIndexFromRedis(type);
		for (PositionData index: pdList) {

			handleCraneDataBatchFromHttp(index,"2021-03-28 00:30:00","2021-04-13 00:30:00");
		}
	}

	public void handleCraneDataBatchFromHttp(PositionData index,String start,String end){
		//振弦数据
		String vgKey = "sensor:" + index.getPositionId() + ":" + StressConstant.STRESS_SENSOR_TYPE_VIBRATING;
		FirstData fdVg = bladeRedis.get(vgKey);
		PageResData prdVg = getDataFromHttpRequest(fdVg.getSensorCode(),fdVg.getChannelCode(),start,end);
		System.out.println("----------------------"+prdVg.getList().size());
		int totalCount = prdVg.getTotalCount();
		int pageSize = prdVg.getPageSize();
		int totalPage = prdVg.getTotalPage();
		int currPage = 0;

		List<ResData> rList = new ArrayList<>();

		for (int i = 0; i < totalPage; i++) {
			currPage = i+ 1;
			PageResData prdlist =getDataFromHttpRequestByPage(fdVg.getSensorCode(),fdVg.getChannelCode(),start,end,currPage);
			rList.addAll(prdlist.getList());
		}

		System.out.println("-+++++++++++++++++++++++++++++---"+rList.size());


	}


	public void handlePositionValueInsertBatchMysql(String positionId){

	}

	//从Redis获取起重机实时数据
	public List<CraneData> getResDataFromRedis(Integer type){
		List<CraneData> list = new ArrayList<>();
		List<Device> deviceList = deviceService.list(Wrappers.<Device>query().lambda().eq(Device::getDeviceType, type));
		if (deviceList.size() > 0){
			Device device = deviceList.get(0);
			String deviceId = device.getId().toString();

			//获取设备的传感器索引列表
			List<IndexData> indexDataList = bladeRedis.get("index:" + deviceId);
			for (IndexData index: indexDataList) {
				String sensorChannelCode = index.getSensorCode() + ":" + index.getChannelCode();
				ResData resData = bladeRedis.get(sensorChannelCode);
				CraneData td = new CraneData();
				td.setStatusTypeName(index.getStatusTypeName());
				td.setName(index.getSensorName());
				td.setChannelId(index.getSensorId());
				td.setSampleValue(resData.getPntValue());
				list.add(td);
			}
		}
		return list;
	}


	//从Redis获取起重机实时数据
	public List<CraneData> getCraneDataFromRedis(Integer type){
		List<CraneData> list = new ArrayList<>();
		List<Device> deviceList = deviceService.list(Wrappers.<Device>query().lambda().eq(Device::getDeviceType, StressConstant.STRESS_DEVICE_TYPE_TOWER_CRANE));
		if (deviceList.size() > 0){
			Device device = deviceList.get(0);
			String deviceId = device.getId().toString();
			List<ChannelVO> tree = channelService.listVibrationSensor(device.getId());
			for (ChannelVO ch: tree) {
				//生成key
				String key = "id:" + deviceId + ":" + ch.getChannelId();
				//得到key = sensorCode:channelCode
				String sensorChannelCode = bladeRedis.get(key);
				//获取值 反序列化
				ReceiveData receiveData = JsonUtil.parse(bladeRedis.get(sensorChannelCode).toString(),ReceiveData.class);

				CraneData td = new CraneData();
				td.setStatusTypeName(ch.getStatusTypeName());
				td.setName(ch.getName());
				td.setChannelId(ch.getChannelId().toString());
				td.setSampleValue(receiveData.getPntValue());
				list.add(td);
			}
		}
		return list;
	}

	public void insertCraneDataToRedis(String sensorCode,String channelCode){
		//1、采集仪
		List<Sensor> sensorList = sensorService.list(Wrappers.<Sensor>query().lambda().eq(Sensor::getCode,sensorCode)
			.eq(Sensor::getSensorType,StressConstant.STRESS_SENSOR_TYPE_ACQUISITION));
		if (sensorList.size() > 0){
			Sensor sensor = sensorList.get(0);
			List<Sensor> list = sensorService.list(Wrappers.<Sensor>query().lambda().eq(Sensor::getParentId,sensor.getId())
				.eq(Sensor::getCode,channelCode));
			if (list.size() > 0){
				Sensor sensorKey = list.get(0);
				List<Channel> channelList = channelService.list(Wrappers.<Channel>query().lambda().eq(Channel::getChannelId,sensorKey.getPositionId()));
				if (channelList.size() > 0){

				}
			}
		}
	}

	//处理最新数据，保证数据是最新，目的是推送到前段
	public void handleReceiveData(String sensorCode,String channelCode,ResData newData){
		String sensorChannelCode = "online" + sensorCode +":"+ channelCode;
		Boolean keyExsited= bladeRedis.exists(sensorChannelCode);

		if(keyExsited){//有数据
			System.out.println("--------------------存在");
			//获取值 反序列化
			ResData oldData = bladeRedis.get(sensorChannelCode);
			LocalDateTime oldTime = DateTimeUtil.parseDateTime(oldData.getCreated());
			LocalDateTime newTime = DateTimeUtil.parseDateTime(newData.getCreated());
			if (newTime.isAfter(oldTime)){
				bladeRedis.set(sensorChannelCode,newData);
			}
		}else {//没有该数据，插入
			System.out.println("---------------------不存在");
			bladeRedis.set(sensorChannelCode,newData);
		}
	}

	//@Scheduled(cron = "*/20 * * * * ?")//每30秒触发
	//@Async
	public void getDataFromHttp(){
		List<Device> deviceList = deviceService.list(Wrappers.<Device>query().lambda().eq(Device::getDeviceType, StressConstant.STRESS_DEVICE_TYPE_TOWER_CRANE));
		if (deviceList.size() > 0) {
			Device device = deviceList.get(0);
			String deviceId = device.getId().toString();
			String indexDeviceKey = "index:" + deviceId;
			List<IndexData> list = bladeRedis.get(indexDeviceKey);
			for (IndexData data: list) {
				String sensorCode = data.getSensorCode();
				String channelCode = data.getChannelCode();
				sendHttpRequest(sensorCode,channelCode);
			}
		}
	}

	public void sendHttpRequest(String sensorCode,String channelCode){
		HttpQueryData query = new HttpQueryData();
		query.setChannel(channelCode);
		query.setNode(sensorCode);
		query.setStart("2021-03-28 00:30:00");
		query.setEnd("2021-04-03 00:00:30");
		query.setPage(1);
		String opt1 =HttpRequest.post(URI.create("http://182.92.232.25:6830/partner/channel"))
			.bodyJson(query).execute().onSuccessful(ResponseSpec::asString);
		System.out.println(opt1);
		QueryResult qr = JsonUtil.parse(opt1,QueryResult.class);
		PageResData pgd = qr.getData();
		for (ResData resdata:pgd.getList()) {
			//插入缓存最新数据
			handleReceiveData(sensorCode,channelCode,resdata);
		}
	}
//	@Scheduled(cron = "*/30 * * * * ?")//每30秒触发
//	@Async
	public void getHttpRequest(){
		HttpQueryData query = new HttpQueryData();
		query.setChannel("60001");
		query.setNode("6000003");
		query.setStart("2021-03-28 00:30:00");
		query.setEnd("2021-04-13 00:00:30");
		query.setPage(1);
		String opt1 =HttpRequest.post(URI.create("http://182.92.232.25:6830/partner/channel"))
			.bodyJson(query).execute().onSuccessful(ResponseSpec::asString);
		System.out.println(opt1);
		QueryResult qr = JsonUtil.parse(opt1,QueryResult.class);
		PageResData pgd = qr.getData();
		System.out.println(pgd.toString());

//		PageResData prdVg = getDataFromHttpRequest("95000038","60004","2021-03-28 00:30:00","2021-04-13 00:00:30");
//		System.out.println("----------------------"+prdVg.getTotalCount());
//		int totalCount = prdVg.getTotalCount();
//		int pageSize = prdVg.getPageSize();
//		int totalPage = prdVg.getTotalPage();
//		int currPage = 0;
//
//		List<ResData> rList = new ArrayList<>();
//
//		for (int i = 0; i < totalPage; i++) {
//			currPage = i+ 1;
//			PageResData prdlist =getDataFromHttpRequestByPage("95000038","60004","2021-03-28 00:30:00","2021-04-13 00:00:30",currPage);
//			rList.addAll(prdlist.getList());
//		}
	}

//	@Scheduled(cron = "*/50 * * * * ?")//每30秒触发
//	@Async
	public void handle(){
//		List<Sensor> list = sensorService.list(Wrappers.<Sensor>query().lambda().gt(Sensor::getSensorType, StressConstant.STRESS_SENSOR_TYPE_POSITION));
//		for (Sensor s: list) {
//			sensorService.updateSensor(s);
//		}
		//解析时间 //2021-03-28 00:30:00  1616862600010
//		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		long currentTime = System.currentTimeMillis();
//		long startTime = currentTime - 1000 * 60 * 60 * 24 * 15 - 1000 * 60 * 60 * 20 ;//13 * 24 * 48 * 30 * 60 * 1000
//		Date endDate = new Date(currentTime);
//		Date startDate = new Date(startTime);
//
//		//确定时间范围
//		String end = df.format(startDate);
//		System.out.println(end);
//		System.out.println(startTime);
//		long currentTime = System.currentTimeMillis();
//		long time = 1616862500000L;
//		long startTime  = 0L;
//		long updateTime = 0L;
//		long inval = 1000 * 60 * 30;
//		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		for (int i = 0; i < 760; i++) {
//			startTime =  time + inval * i;
//			updateTime =  time + inval * (i+1);
//			String startDate = df.format(new Date(startTime));
//			String updateDate = df.format(new Date(startTime));
//
//			System.out.println(df.format(new Date(startTime)));
//			System.out.println(df.format(new Date(updateTime)));
//			System.out.println("------------------------------");
//			if (startTime > currentTime) break;
//		}

		System.out.println("-----------------------------------------------------------------------------------------");
	}

}
